package com.dlshouwen.wzgl.servlet;

import com.dlshouwen.core.base.config.CONFIG;
import com.dlshouwen.core.base.model.SessionUser;
import com.dlshouwen.core.base.utils.AttributeUtils;
import com.dlshouwen.core.base.utils.ConvertVideo;
import com.dlshouwen.core.base.utils.ConvertVideoThread;
import com.dlshouwen.core.base.utils.SpringUtils;
import com.dlshouwen.core.base.utils.SysConfigLoader;
import com.dlshouwen.wzgl.picture.dao.PictureDao;
import com.dlshouwen.wzgl.picture.model.Picture;

import net.sf.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;

/**
 * servlet上传文件处理
 * @author cuixubin
 */
@WebServlet(name = "uploadPic", urlPatterns = { "/uploadPic" })
public class UploadPic extends HttpServlet {
	private static final long serialVersionUID = -4593909857975163511L;
	private static final String IMGTYPE = "jpg_jpeg_bmp_gif_png_tiff_JPG_JPEG_PNG_BMP_GIF_TIFF";
	private static final String VIDEOTYPE = "avi_wmv_mpeg_mp4_mov_mkv_flv_f4v_m4v_rmvb_rm_3gp_dat_ts_mts_vob";

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doProcess(request, response);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doProcess(req, resp);
	}
	
	private void doProcess(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String albumId = request.getParameter("albumId");
		// String articleId = request.getParameter("articleId");
		String type = request.getParameter("albumFlag");
		// String isFile = request.getParameter("isFile");
		// String isVideo = request.getParameter("isVideo");
		PictureDao pictureDao = null;
		try {
			pictureDao = (PictureDao) SpringUtils.getBean("pictureDao");
		} catch (Exception ex) {
			Logger.getLogger(UploadPic.class.getName()).log(Level.SEVERE, null, ex);
		}

		// 临时文件目录
		String tempPath = SysConfigLoader.getSystemConfig().getProperty("imageTemp", "C:\\files\\temp");
		// 创建临时文件夹
		File dirTempFile = new File(tempPath);
		if (!dirTempFile.exists()) {
			dirTempFile.mkdirs();
		}
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setSizeThreshold(20 * 1024 * 1024); // 设定使用内存超过5M时，将产生临时文件并存储于临时目录中。
		factory.setRepository(new File(tempPath)); // 设定存储临时文件的目录。
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("UTF-8");
		try {
			List<FileItem> items = upload.parseRequest(request);
			Iterator<FileItem> itr = items.iterator();
			while (itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				String fileName = item.getName();//文件名
				if (!item.isFormField() && StringUtils.isNotEmpty(fileName)) {
					InputStream is = null;
					FileOutputStream fos = null;
					//文件名（不带后缀）
					String fplainName = fileName.substring(0, fileName.lastIndexOf("."));
					//文件后缀
					String fsuf = fileName.substring(fileName.lastIndexOf(".") + 1);
					//保存文件的物理路径
					String realPath = CONFIG.SOURCE_REAL_PATH;
					//返回的访问路径名+文件名
			        String filePath = CONFIG.UPLOAD_FILE_PATH;
					//文件是否是视频
					boolean ifVideo = false;
					//视频封面
					String coverPath = "";
					if(null != fsuf && !"".equals(fsuf)) {
			            if(IMGTYPE.contains(fsuf)) {
			            	realPath += CONFIG.UPLOAD_PIC_PATH;
			                filePath = CONFIG.UPLOAD_PIC_PATH;
			            }else if(VIDEOTYPE.contains(fsuf)) {
			            	realPath += CONFIG.UPLOAD_VIDEO_PATH;
			                filePath = CONFIG.UPLOAD_VIDEO_PATH;
			                coverPath = CONFIG.UPLOAD_VIDEO_PATH;
			                ifVideo = true;
			            }else {
			            	realPath += CONFIG.UPLOAD_FILE_PATH;
			                filePath = CONFIG.UPLOAD_FILE_PATH;
			            }
			        }
					synchronized (this) {
						try {
							is = item.getInputStream();
							//重命名文件名
							String newFileName = fplainName + "_" + new Date().getTime() + ".";
							
							if(ifVideo) {
								fileName = realPath + "/" + newFileName + fsuf;
								coverPath = filePath + "/" + newFileName + "jpg";
								newFileName += "flv";
							}else {
								newFileName += fsuf;
								fileName = realPath + "/" + newFileName;
							}
							filePath += "/" + newFileName;
							
//							fileName = fplainName + "_" + new Date().getTime() + ".";
							
							//创建文件夹
							File file = new File(realPath);
							if (!file.exists()) {
								file.mkdirs();
							}
							//创建文件
							file = new File(fileName);
							if (!file.exists()) {
								file.createNewFile();
							}
							//存储文件到磁盘
							byte[] buffer = new byte[1024];
							int read = 0;
							fos = new FileOutputStream(file);
							while ((read = is.read(buffer)) != -1) {
								fos.write(buffer, 0, read);
							}
							fos.flush();
							
							String path = AttributeUtils.getAttributeContent(request.getServletContext(),
									"source_webapp_file_postion") + filePath;

							if (albumId != null && albumId.trim().length() > 0) {
								Picture pic = new Picture();
								if (type != null) {
									pic.setFlag(type);
								}
								pic.setPicture_name(fileName);
								pic.setPath(filePath);
								pic.setAlbum_id(albumId);
								pic.setCreate_time(new Date());
								SessionUser sessionUser = (SessionUser) request.getSession()
										.getAttribute(CONFIG.SESSION_USER);
								String userName = sessionUser.getUser_name();
								pic.setUser_name(userName);
								pictureDao.insertPicture(pic);
							}
							
							String json = "{ \"state\": \"SUCCESS\",\"url\": \"" + path + "\",\"title\": \"" + newFileName
									+ "\",\"original\": \"" + newFileName + "\"";
							if(StringUtils.isNotEmpty(coverPath)) {
								String videoTime = ConvertVideo.getMovieTime(fileName);
								String toPath = fileName.substring(0, fileName.lastIndexOf("/"));
					            Thread thread = new Thread(new ConvertVideoThread(fileName, toPath));
					            thread.start();
					            json += ",\"videoTime\": \""+videoTime+"\"";
					            json += ",\"videoCoverPath\": \""+coverPath+"\"";
							}
							json += "}";

							response.setContentType("text/html;charset=utf-8");
							response.setCharacterEncoding("UTF-8");
							response.getWriter().print(json);
						} catch (Exception ex) {
							java.util.logging.Logger.getLogger(UploadPic.class.getName()).log(Level.SEVERE, null, ex);
						} finally {
							if (is != null) {
								is.close();
							}
						}
					}
				}
			}

		} catch (FileUploadException e) {
			e.printStackTrace();
		}
	}
}
